package gate

import (
	//"bytes"
	//"encoding/binary"
	"fmt"
	//"github.com/golang/protobuf/proto"
	"github.com/gorilla/websocket"
	"github.com/liu-junyong/go-logger/logger"
	//"log"
	//"net"
	"sync"
	"time"
	//"bufio"
	"bufio"
	//"encoding/base64"
	"net"
)

type UserSession struct {
	LastPing int64
	Tick     int64  //来自token
	UserID   int32  //来自token
	NickName string //来自token
	RoomID   int32  //来自token
	Ws       *websocket.Conn
	//Rw     *bufio.ReadWriter
	wsWritelock  sync.Mutex
	ConnectionID string
	ClientID     string
	GameServerID string
	CM           *ConnectionManager
}

type ConnectionManager struct {
	lock    sync.Mutex
	//ID2RW   map[string]*bufio.ReadWriter
	ID2Conn map[string]*net.Conn
}

//func (this *ConnectionManager) GetConnection(client string,data []byte,UserID int32) {
func (this *ConnectionManager) Getonnection(client string)*net.Conn {
	defer func() {
		if r := recover(); r != nil {
			logger.Error(r)
		}
	}()

	this.lock.Lock()
	defer this.lock.Unlock()
	return this.ID2Conn[client]
}

func (this *ConnectionManager) OnConnection(client string, connection *bufio.ReadWriter, conn *net.Conn) {
	defer func() {
		if r := recover(); r != nil {
			logger.Error(r)
		}
	}()

	this.lock.Lock()
	defer this.lock.Unlock()
	//this.ID2RW[client] = connection
	this.ID2Conn[client] = conn
}

func (this *ConnectionManager) OnDisConnection(client string, reason string) {
	defer func() {
		if r := recover(); r != nil {
			logger.Error(r)
		}
	}()
	logger.Info(client, "断开连接:", reason)
	this.lock.Lock()
	defer this.lock.Unlock()
	//delete(this.ID2RW, client)
	delete(this.ID2Conn, client)
}

func (this *ConnectionManager) DisConnectionWithoutLock(client string, reason string) {
	defer func() {
		if r := recover(); r != nil {
			logger.Error(r)
		}
	}()
	logger.Info(client, "主动断开连接:", reason)
	//this.lock.Lock()
	//defer this.lock.Unlock()
	c := this.ID2Conn[client]
	if c != nil {
		(*c).Close()
	}
}


func (this *ConnectionManager) DisConnection(client string, reason string) {
	defer func() {
		if r := recover(); r != nil {
			logger.Error(r)
		}
	}()
	logger.Info(client, "主动断开连接:", reason)
	this.lock.Lock()
	defer this.lock.Unlock()
	c := this.ID2Conn[client]
	if c != nil {
		(*c).Close()
	}
}


func (this *ConnectionManager) Init() {
	//this.ID2RW = make(map[string]*bufio.ReadWriter)
	this.ID2Conn = make(map[string]*net.Conn)
}

func (this *UserSession) WritePong(messagetype int) {
	this.wsWritelock.Lock()
	defer this.wsWritelock.Unlock()
	this.Ws.SetWriteDeadline(time.Now().Add(6 * time.Second))
	err := this.Ws.WriteMessage(messagetype, []byte("1"))
	if err != nil {
		logger.Info(fmt.Sprintf("player:%d  error:%v", this.UserID, err))
	}
}

func (this *UserSession) CheckKeepalive(now int64, loggerError bool) bool {

	defer func() {
		if r := recover(); r != nil {
			logger.Error(r)
		}
	}()

	if this.RoomID > 0 {
		diff := now - this.LastPing
		if diff > 10 && diff < 10000 && this.Ws != nil {
			if loggerError {
				logger.Error(fmt.Sprintf("UserID[%d] Room[%d] [%d]秒没有收到心跳", this.UserID, this.RoomID, diff))
			} else {
				logger.Info(fmt.Sprintf("UserID[%d] Room[%d]  [%d]秒没有活跃", this.UserID, this.RoomID, diff))
			}
		}

		if diff > 10 && diff < 100000 {
			return false
		}
	}
	return true

}

